//
//  XLNetworkTools.swift
//  XLVeibo
//
//  Created by macbook on 16/6/26.
//  Copyright © 2016年 buWangChuXing. All rights reserved.
//

import UIKit

import AFNetworking

//请求方式用枚举
enum MethodType: String{

    case GET = "GET"
    case POST = "POST"
}


//给成功，失败 返回的闭包起别名
typealias SuccessClosure = (response: AnyObject?)->()
typealias FailureClosure = (error: NSError)->()

class XLNetworkTools: AFHTTPSessionManager {
    
    //全局访问点
    static let sharedTools:XLNetworkTools = {
    
        let tools = XLNetworkTools()
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
       return tools
    }()
    
    
    
    func request(method:MethodType,urlString:String,parameters:AnyObject?,success:(reponse:AnyObject?)->(),failure:(error:NSError)->()){
    
        //GET 
        if method == .GET {
            
            self.GET(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                
                success(reponse: res)
                
                }, failure: { (_, err) in
                    
                    failure(error: err)
            })
            
        }else{
        
            //POST请求
            self.POST(urlString, parameters: parameters, progress: nil, success: { (_, res) in
                
                success(reponse: res)
                
                }, failure: { (_, err) in
                    
                    failure(error: err)
            })
        }
    
    }
    
}

extension XLNetworkTools{

    //请求token
    func oauthLoadUserAccout(code: String,success:(response:AnyObject?)->(),failure:(error: NSError)->()){
    
        //请求URL
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //请求参数
        /**
         client_id	true	string	申请应用时分配的AppKey。
         client_secret	true	string	申请应用时分配的AppSecret。
         grant_type	true	string	请求的类型，填写authorization_code
         
         grant_type为authorization_code时
         必选	类型及范围	说明
         code	true	string	调用authorize获得的code值。
         redirect_uri	true	string	回调地址，需需与注册应用里的回调地址一致。         */
    
        let parameters = [
        
            "client_id" : APPKEY,
            "client_secret" : APPSECRET,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : REDIRECT_URI
        
        ]
        
        self.request(MethodType.POST, urlString: urlString, parameters: parameters, success: success, failure: failure)
    }
    
    
    //请求个人信息数据
    func oauthLoadUserInfo(userAccont:XLUserAccount,sucess:SuccessClosure,failure:FailureClosure){
        
        //请求URL
        let urlString = "https://api.weibo.com/2/users/show.json"
        
        //请求参数
        let params = [
            "access_token":userAccont.access_token!,
            "uid":userAccont.uid!
        ]
        
        self.request(.GET, urlString: urlString, parameters: params, success:sucess , failure: failure)
    
  }
}



extension XLNetworkTools{

    //首页的数据
    func homeLoadStatusData(sinceId:Int64,maxId:Int64,success: SuccessClosure,failure:FailureClosure){
    
        //请求URL
        let url = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        //请求参数
        let parames = [
            "access_token":XLUserAccountTools.sharedTools.accessToken!,
            "since_id":"\(sinceId)",
            "max_id":"\(maxId)"
        ]
        
        //发送请求
        request(.GET, urlString: url, parameters: parames, success: success, failure: failure)
    }
}

extension XLNetworkTools{

    //发布微博只有文字
    func composeSendMessage(status:String,success:SuccessClosure,failure:FailureClosure){
    
        //url
        let url = "https://api.weibo.com/2/statuses/update.json"
        //请求擦数
        let parames = [
        "access_token":XLUserAccountTools.sharedTools.accessToken!,
        "status":status
        ]
        
        request(.POST, urlString: url, parameters: parames, success: success, failure: failure)
        
    }
    
    /**
       发布一条带图片的微博，只允许我们发布一张图片
     */
    func sendeMessageWithPicture(status:String,imageList:[UIImage],success:(response:AnyObject?)->(),failure:(error:NSError)->() ){
    
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let parames = [
        
            "access_token":XLUserAccountTools.sharedTools.accessToken!,
            "status":status
          ]
        
        
        
        POST(url, parameters: parames, constructingBodyWithBlock: { (formdata) in
            
            //遍历数组
            for image in imageList{
            
                //图片转二进制
                let data = UIImagePNGRepresentation(image)
                
                formdata.appendPartWithFileData(data!, name: "pic", fileName: "asd", mimeType: "application/octet-stream")
            
            }
            
             
            }, progress: nil, success: { (_, responst) in
                success(response: responst)
            }) { (_, error) in
                failure(error: error)
        }
    
    }
}






















